<template>
  <div 
    class="recipient-selector" 
    :class="{ 'focused': isFocused }"
    @click="focusInput"
  >
    <div class="recipient-container">
      <!-- 已选收件人标签 -->
      <template v-for="(recipient, index) in modelValue" :key="index">
        <div class="recipient-tag" :class="{ 'editing': editingIndex === index }">
          <template v-if="editingIndex !== index">
            <span class="recipient-tag-text" @click.stop="editRecipient(index)">
              {{ getDisplayName(recipient) }}
            </span>
            <span class="recipient-tag-remove" @click.stop="removeRecipient(index)">×</span>
          </template>
          <template v-else>
            <input
              :ref="el => { if (el) inlineEditRefs[index] = el }"
              v-model="editValue"
              type="text"
              class="recipient-inline-edit"
              @keydown="handleEditKeyDown"
              @blur="handleEditBlur"
              @click.stop
            />
          </template>
        </div>
      </template>

      <!-- 输入框 -->
      <div class="input-container" :class="{ 'has-recipients': modelValue.length > 0 }">
        <input
          ref="inputRef"
          v-model="inputValue"
          type="text"
          class="recipient-input"
          :placeholder="placeholder"
          @focus="handleFocus"
          @blur="handleBlur"
          @input="handleInput"
          @keydown="handleKeyDown"
          @mouseenter="handleMouseEnter"
          @click.stop
        />
      </div>
    </div>

    <!-- 下拉菜单 -->
    <div v-show="showDropdown && filteredContacts.length > 0" class="dropdown-menu">
      <div
        v-for="(contact, index) in filteredContacts"
        :key="contact.id"
        class="dropdown-item"
        :class="{ 'selected': selectedIndex === index }"
        @click.stop.prevent="selectContact(contact, $event)"
        @mouseover="selectedIndex = index"
      >
        <div class="contact-name">
          <span>{{ contact.name }}</span>
          <span v-if="contact.emailAccount">{{  `<${contact.emailAccount}>` }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { useEventListener } from '@vueuse/core';
import api from '/@/api/email';

// Props
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  placeholder: {
    type: String,
    default: '请输入收件人邮箱'
  },
  contacts: {
    type: Array,
    default: () => []
  }
});

// Emits
const emit = defineEmits([
  'update:modelValue',
  'focus',
  'blur',
  'input'
]);

// Refs
const inputRef = ref(null);
const inlineEditRefs = ref({});
const inputValue = ref('');
const editValue = ref('');
const isFocused = ref(false);
const showDropdown = ref(false);
const selectedIndex = ref(-1);
const editingIndex = ref(-1);
const isProcessingEdit = ref(false);
const contactList = ref([]);

// 获取联系人列表
onMounted(async () => {
  try {
    const response = await api.contact.getList({
      account: localStorage.getItem('curAccount')
    });
    contactList.value = response.data || [];
  } catch (error) {
    console.error('获取联系人失败', error);
  }
});

// 计算属性
const allContacts = computed(() => {
  // 合并传入的联系人和从API获取的联系人
  return [...props.contacts, ...contactList.value];
});

const filteredContacts = computed(() => {
  // 当输入为空时，返回空数组（不显示任何联系人）
  if (!inputValue.value) {
    return [];
  }
  
  const query = inputValue.value.toLowerCase().trim();
  
  // 首先尝试精确匹配开头
  const startsWithMatches = allContacts.value.filter(contact => {
    const name = (contact.name || '').toLowerCase();
    const email = (contact.emailAccount || contact.email || contact.id || '').toLowerCase();
    return name.startsWith(query) || email.startsWith(query);
  });
  
  // 然后尝试包含匹配
  const containsMatches = allContacts.value.filter(contact => {
    const name = (contact.name || '').toLowerCase();
    const email = (contact.emailAccount || contact.email || contact.id || '').toLowerCase();
    return (name.includes(query) || email.includes(query)) && 
           !name.startsWith(query) && !email.startsWith(query);
  });
  
  // 组合结果，优先显示精确匹配的开头
  return [...startsWithMatches, ...containsMatches].slice(0, 10);
});

console.log("filteredContacts:", filteredContacts)
// 方法
const focusInput = () => {
  if (editingIndex.value === -1 && inputRef.value) {
    inputRef.value.focus();
  }
};

const handleFocus = () => {
  isFocused.value = true;
  showDropdown.value = true;
  console.log('focus-focus-focus')
  emit('focus');
};

const handleBlur = () => {
  // 延迟处理失焦事件，以便点击下拉项目时能够先触发选择
  setTimeout(() => {
    isFocused.value = false;
    showDropdown.value = false;
    
    // 如果用户在编辑时移开了焦点，取消编辑
    if (editingIndex.value !== -1) {
      cancelEdit();
    }
    
    // 如果输入框有值并且是有效的邮箱，添加为收件人
    addInputValueIfValid();
    
    emit('blur');
  }, 150);
};

const handleInput = (event) => {
  showDropdown.value = true;
  selectedIndex.value = -1;
  emit('input', event);
};

const handleKeyDown = (event) => {
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault();
      handleArrowDown();
      break;
    case 'ArrowUp':
      event.preventDefault();
      handleArrowUp();
      break;
    case 'Enter':
      event.preventDefault();
      handleEnter();
      break;
    case 'Tab':
      // 如果有输入内容，Tab键添加收件人
      if (inputValue.value.trim()) {
        event.preventDefault();
        addInputValueIfValid();
      }
      break;
    case 'Escape':
      event.preventDefault();
      showDropdown.value = false;
      break;
    case 'Backspace':
      // 如果输入框为空，删除最后一个收件人
      if (!inputValue.value && props.modelValue.length > 0 && editingIndex.value === -1) {
        event.preventDefault();
        editRecipient(props.modelValue.length - 1);
      }
      break;
  }
};

const handleArrowDown = () => {
  if (filteredContacts.value.length === 0) return;
  selectedIndex.value = Math.min(selectedIndex.value + 1, filteredContacts.value.length - 1);
  if (selectedIndex.value === -1) selectedIndex.value = 0;
};

const handleArrowUp = () => {
  if (filteredContacts.value.length === 0) return;
  selectedIndex.value = Math.max(selectedIndex.value - 1, -1);
};

const handleEnter = () => {
  if (selectedIndex.value !== -1 && filteredContacts.value[selectedIndex.value]) {
    selectContact(filteredContacts.value[selectedIndex.value], null);
  } else {
    addInputValueIfValid();
  }
};

const addInputValueIfValid = () => {
  const value = inputValue.value.trim();
  if (value && isValidEmail(value)) {
    addRecipient(value);
    clearInput();
  }
};

const handleEditKeyDown = (event) => {
  switch (event.key) {
    case 'Enter':
      event.preventDefault();
      confirmEdit();
      break;
    case 'Escape':
      event.preventDefault();
      cancelEdit();
      break;
    case 'Tab':
      // Tab键确认编辑并移到下一个元素
      event.preventDefault();
      confirmEdit();
      nextTick(() => {
        focusInput();
      });
      break;
  }
};

const handleEditBlur = () => {
  // 当内联编辑输入框失去焦点时确认编辑
  // 使用setTimeout避免与点击事件冲突
  setTimeout(() => {
    if (editingIndex.value !== -1) {
      confirmEdit();
    }
  }, 100);
};

const addRecipient = (value) => {
  // 检查是否已存在相同的收件人
  if (!props.modelValue.includes(value)) {
    emit('update:modelValue', [...props.modelValue, value]);
  }
};

const removeRecipient = (index) => {
  const updatedRecipients = [...props.modelValue];
  updatedRecipients.splice(index, 1);
  emit('update:modelValue', updatedRecipients);
  
  // 如果删除的是正在编辑的收件人，取消编辑状态
  if (editingIndex.value === index) {
    editingIndex.value = -1;
    editValue.value = '';
  } else if (editingIndex.value > index) {
    // 如果删除的是编辑索引之前的项，需要调整编辑索引
    editingIndex.value--;
  }
  
  // 重新聚焦到输入框
  nextTick(focusInput);
};

const selectContact = (contact, event) => {
  // 阻止事件冒泡
  if (event) {
    event.stopPropagation();
  }

  console.log("contact:", contact)
  
  // 使用ID或email作为值emailAccount
  const value = contact.emailAccount || contact.email || contact.id;
  addRecipient(value);
  
  // 清空输入框并聚焦，但不隐藏下拉菜单
  clearInput();
  
  // 延迟一小段时间后再聚焦，避免冲突
  setTimeout(() => {
    if (inputRef.value) {
      inputRef.value.focus();
    }
  }, 50);
};

const editRecipient = (index) => {
  // 防止重复触发
  if (isProcessingEdit.value || index < 0 || index >= props.modelValue.length) {
    return;
  }
  
  isProcessingEdit.value = true;
  
  // 如果之前有未完成的编辑，先取消
  if (editingIndex.value !== -1) {
    cancelEdit();
  }
  
  // 设置编辑状态和值
  editingIndex.value = index;
  const recipientId = props.modelValue[index]; // 先声明recipientId变量
  editValue.value = getDisplayName(recipientId); // 使用getDisplayName获取友好名称
  
  console.log('index:', index)
  console.log(props.modelValue)
  console.log("editValue:", props.modelValue[index])
  
  // 确保DOM更新后再聚焦
  nextTick(() => {
    const editInput = inlineEditRefs.value[index];
    console.log(editInput)
    if (editInput) {
      editInput.focus();
      editInput.select();
    }
    
    // 短暂延迟后允许再次编辑，避免快速点击导致的问题
    setTimeout(() => {
      isProcessingEdit.value = false;
    }, 200);
  });
};

const confirmEdit = () => {
  if (editingIndex.value !== -1) {
    const value = editValue.value.trim();
    
    // 仅在编辑值有效时更新
    if (value && isValidEmail(value)) {
      const updatedRecipients = [...props.modelValue];
      updatedRecipients[editingIndex.value] = value;
      emit('update:modelValue', updatedRecipients);
    }
    
    // 无论如何都重置编辑状态
    editingIndex.value = -1;
    editValue.value = '';
  }
};

const cancelEdit = () => {
  if (editingIndex.value !== -1) {
    editingIndex.value = -1;
    editValue.value = '';
  }
};

const clearInput = () => {
  inputValue.value = '';
  selectedIndex.value = -1;
  
  // 多层保障确保输入框被清空
  nextTick(() => {
    inputValue.value = '';
  });
  
  setTimeout(() => {
    inputValue.value = '';
  }, 0);
  
  setTimeout(() => {
    inputValue.value = '';
  }, 50);
};

const getDisplayName = (recipient) => {
  // 查找匹配的联系人显示友好名称
  const contact = allContacts.value.find(c => (c.id === recipient || c.email === recipient));
  return contact ? (contact.name || recipient) : recipient;
};

const isValidEmail = (email) => {
  // 简单的邮箱验证
  const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailPattern.test(email);
};

const handleMouseEnter = () => {
  if (inputRef.value && inputRef.value === document.activeElement) {
    showDropdown.value = true;
  }
};

// 监听事件
useEventListener(document, 'click', (event) => {
  // 检查点击是否在组件外部
  const selectorEl = document.querySelector('.recipient-selector');
  const dropdownEl = document.querySelector('.dropdown-menu');
  
  // 如果点击事件不是发生在选择器或下拉菜单内，则隐藏下拉
  if (selectorEl && 
      !selectorEl.contains(event.target) || 
      (dropdownEl && dropdownEl.contains(event.target))) {
    showDropdown.value = false;
  }
});

// 监听模型变化，当收件人列表变化时重置状态
watch(() => props.modelValue, () => {
  if (editingIndex.value !== -1 && editingIndex.value >= props.modelValue.length) {
    editingIndex.value = -1;
    editValue.value = '';
  }
}, { deep: true });

// 清理工作
onBeforeUnmount(() => {
  inlineEditRefs.value = {};
});
</script>

<style lang="scss" scoped>
.recipient-selector {
  position: relative;
  width: 100%;
  // border: 1px solid #ddd;
  border-radius: 4px;
  min-height: 36px;
  padding: 4px 8px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  cursor: text;
  transition: border-color 0.3s;
  // background-color: #fff;
  
  &.focused {
    // border-color: #1e88e5;
    box-shadow: 0 0 0 2px rgba(30, 136, 229, 0.2);
  }
}

.recipient-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
}

.recipient-tag {
  background-color: #f0f0f0;
  border-radius: 3px;
  margin: 2px 4px 2px 0;
  padding: 2px 6px;
  display: inline-flex;
  align-items: center;
  max-width: 100%;
  position: relative;
  height: 26px;
  
  &.editing {
    background-color: transparent;
    padding: 0;
  }
  
  .recipient-tag-text {
    margin-right: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px;
    cursor: text;
    color: #333;
  }
  
  .recipient-tag-remove {
    cursor: pointer;
    color: #999;
    font-size: 16px;
    line-height: 1;
    margin-left: 2px;
    
    &:hover {
      color: #f44336;
    }
  }
}

.recipient-inline-edit {
  min-width: 100px;
  border: 1px solid #1e88e5;
  border-radius: 3px;
  padding: 2px 4px;
  height: 26px;
  outline: none;
}

.input-container {
  flex: 1;
  min-width: 120px;
  
  &.has-recipients {
    margin-left: 4px;
  }
  
  .recipient-input {
    border: none;
    outline: none;
    width: 100%;
    padding: 4px 0;
    background: transparent;
    font-size: 14px;
  }
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  max-height: 250px;
  overflow-y: auto;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  margin-top: 4px;
}

.dropdown-item {
  padding: 8px 12px;
  cursor: pointer;
  
  &:hover, &.selected {
    background-color: #f5f5f5;
  }
  
  .contact-name {
    font-weight: 500;
  }
  
  .contact-email {
    font-size: 12px;
    color: #666;
    margin-top: 2px;
  }
}
</style>